import React, {useEffect, useState} from 'react';
import 'antd/dist/antd.css';
import './App.css';
import {Layout, Menu, Icon} from 'antd';
import RuleEdit from "./views/RuleEdit";
import reactHistory from "./utils/reactHistory";
import {Route, Router, Switch} from "react-router";
import JsEdit from "./views/JsEdit";

const {Content, Footer, Sider} = Layout;


function SideMenu(props) {

    const [currentKey, setCurrentKey] = useState("rule");

    function goPage(url, key) {
        setCurrentKey(key);
        reactHistory.push({
            pathname: url
        });
    }

    function initMenuByUrls(urls) {
        if (urls.length >= 2) {
            const pathname = urls[1].split("?")[0];
            console.info("location pathname", pathname);
            if (pathname === "js") {
                setCurrentKey(pathname);
            }
        }
    }

    useEffect(() => {
        const href = window.location.href;
        let urls = href.split("/#/");
        if (urls.length >= 2) {
            initMenuByUrls(urls);
        } else {
            urls = href.split("/ruleEdit#/");
            initMenuByUrls(urls);
        }
    }, []);

    return <Sider
        theme="light"
        style={{
            overflow: 'auto',
            height: '100vh',
            position: 'fixed',
            left: 0,
        }}
    >
        <div className="layout-logo">
            <div>
                <div className={"logo-title-zh"}>海阔视界</div>
                <div className={"logo-title-en"}>{"H I K E R"}</div>
            </div>
        </div>
        <Menu theme="light" mode="inline" selectedKeys={[currentKey]}>
            <Menu.Item key="rule" onClick={() => goPage("/", "rule")}>
                <Icon type="control"/>
                <span className="nav-text">编辑规则</span>
            </Menu.Item>
            <Menu.Item key="js" onClick={() => goPage("/js", "js")}>
                <Icon type="file-text"/>
                <span className="nav-text">编辑插件</span>
            </Menu.Item>
        </Menu>
    </Sider>;
}

function App() {

    return (
        <div className="App">
            <Router history={reactHistory}>
                <Layout>
                    <SideMenu/>
                    <Layout style={{marginLeft: 200}}>
                        <Content style={{margin: '24px 16px 0', overflow: 'initial'}}>
                            <div style={{padding: 24, background: '#fff', minHeight: "calc(100vh - 118px)"}}>
                                <Switch>
                                    <Route path="/js" component={JsEdit}/>
                                    <Route path="/" component={RuleEdit}/>
                                </Switch>
                            </div>
                        </Content>
                        <Footer style={{textAlign: 'center'}}>haikuoshijie.cn © 2020</Footer>
                    </Layout>
                </Layout>
            </Router>
        </div>
    );
}

export default App;
